package com.ruoyi.quartz.task;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.date.DateFormater;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{
    private static Log logger = LogFactory.getLog(RyTask.class);

    public void backupMysqlData() throws IOException {
        // 定义数据库连接信息
        String url = "jdbc:mysql://127.0.0.1:33060/qghome";
        String username = "root";
        String password = "zanysoft";

        // 获取当前日期，格式为 yyyyMMdd
        String currentDate = DateFormater.getSystemCurrentDateSimple();
        // 定义备份文件路径和文件名
        String filePath = RuoYiConfig.getProfile() + "/copy/qghome" + currentDate + ".sql";
        logger.info("备份文件路径：" + filePath);

        try {
            // 连接到MySQL数据库
            Connection connection = DriverManager.getConnection(url, username, password);
            Statement statement = connection.createStatement();
            File file = new File(filePath);
            FileWriter output = new FileWriter(file);

            // 获取所有表名
            String query = "SHOW TABLES";
            statement.executeQuery(query);
            ResultSet rs = statement.getResultSet();
            output.write("SET FOREIGN_KEY_CHECKS=0;\n");

            while (rs.next()) {
                String tableName = rs.getString(1);
                output.write("\n\n--\n-- Table structure for table `" + tableName + "`\n--\n\n");
                query = "SHOW CREATE TABLE " + tableName;
                Statement statement1 = connection.createStatement();
                statement1.executeQuery(query);
                ResultSet rs2 = statement1.getResultSet();
                if (rs2.next()) {
                    String dropTable =  "DROP TABLE IF EXISTS "+tableName;
                    String createTable = rs2.getString(2).replace("CREATE TABLE", "CREATE TABLE");
                    output.write(dropTable + ";\n");
                    output.write(createTable + ";\n");
                }

                output.write("\n\n--\n-- Dumping data for table `" + tableName + "`\n--\n\n");
                query = "SELECT * FROM " + tableName;
                Statement statement2 = connection.createStatement();
                statement2.executeQuery(query);
                ResultSet rs1 = statement2.getResultSet();
                ResultSetMetaData metaData = rs1.getMetaData();
                int columnsCount = metaData.getColumnCount();
                while (rs1.next()) {
                    output.write("INSERT INTO `" + tableName + "` (");
                    for (int i = 1; i <= columnsCount; i++) {
                        output.write("`" + metaData.getColumnName(i) + "`");
                        if (i < columnsCount) {
                            output.write(", ");
                        }
                    }
                    output.write(") VALUES (");
                    for (int i = 1; i <= columnsCount; i++) {
                        String columnValue =  escapeBackslashes(rs1.getString(i))  ;
                        output.write(columnValue);
                        if (i < columnsCount) {
                            output.write(", ");
                        }
                    }
                    output.write(");\n");
                }
            }
            output.close();
            connection.close();
            logger.info("MySQL数据备份成功，文件路径: " + filePath);
        } catch (Exception e) {
            logger.error("MySQL数据备份失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    public static String escapeBackslashes(String str) {
        return (str == null ? "null" : "'" +str.replaceAll("\\\\","\\\\\\\\").replaceAll("'","\\\\'")+ "'");
    }


    public void deleteOldBackups() {
        String backupDir = RuoYiConfig.getProfile() + "/copy/";
        File directory = new File(backupDir);
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                String sevenDaysAgo = DateFormater.getSystemBefore7DaysDateSimple();
                for (File file : files) {
                    if (file.isFile() && file.getName().startsWith("qghome") && file.getName().endsWith(".sql")) {
                        String fileName = file.getName();
                        String fileDate = fileName.substring(fileName.indexOf("qghome") + 6, fileName.indexOf(".sql"));
                        // 删除所有日期小于7天前的文件
                        if (fileDate.compareTo(sevenDaysAgo) < 0) {
                            if (file.delete()) {
                                logger.info("删除旧备份文件: " + file.getName());
                            } else {
                                logger.error("无法删除文件: " + file.getName());
                            }
                        }
                    }
                }
            }
        } else {
            logger.error("备份目录不存在或不是目录: " + backupDir);
        }
    }

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }
}
